package edu.cmu.cs211.snake.gui;

import java.awt.Dimension;
import java.awt.Point;

public class Game {

	private int points;

	private int neaten;

	private Snake snake = new Snake ();

	private FoodManager foodManager;

	private boolean gameOver;

	private Dimension size;

	private static double GROWTH_FACTOR = .25;

	public Game (Dimension size) {
		this.size = size;
		foodManager = new FoodManager (this);
	}

	public int getPoints ()
	{
		return points;
	}

	public int getUpdateSpeed ()
	{
		return Math.max (40, 100 - 3 * (int) Math.sqrt (points));
	}

	public FoodManager getFoodManager ()
	{
		return foodManager;
	}

	public Snake getSnake ()
	{
		return snake;
	}

	public Dimension getSize ()
	{
		return (Dimension) size.clone();
	}

	public boolean isGameOver ()
	{
		return gameOver;
	}

	private boolean moveWillKill (Point p)
	{
		if (snake.getPoints ().contains (p))
			return true;
		if (p.x < 0 || p.y < 0 || p.x >= size.width || p.y >= size.height)
			return true;

		return false;
	}

	public void tick ()
	{
		Point headTarget = snake.startTick();

		if (moveWillKill (headTarget)) {
			onGameOver ();
			return;
		}

		if (foodManager.tryEat (headTarget))
			onEatFood ();

		snake.endTick();

		foodManager.tick ();
	}

	private void onEatFood ()
	{
		points += ++neaten;
		snake.growBy (Math.max (1, (int) (GROWTH_FACTOR * neaten)));
	}

	private void onGameOver ()
	{
		gameOver = true;
	}
}
